package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.DoctorAdapter;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.DictionaryHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.ShopEntityClassify;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.server.ServerCenterShopList.ExpandGridListAdapter;
import com.yksj.healthtalk.ui.views.TagsGridView;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;
/**
 * 最新专家列表
 * @author root
 *
 */
public class ServerCenterDoctorListActivity extends BaseFragmentActivity implements OnClickListener, OnRefreshListener<ListView>, OnItemClickListener, onClickFriendAttentionListener, onClickFriendHeadListener{

	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private DictionaryHelper dictionaryHelper;
	private ArrayList<CustomerInfoEntity> arrayList=new ArrayList<CustomerInfoEntity>();
	private List<Map<String, String>> proList = null;
	private Map<String,List<Map<String, String>>> cityMap = new HashMap<String, List<Map<String, String>>>();
	private DoctorAdapter adapter;
	private int pageNum=1;
	private String id="1"; //商户id
	private AppData mAppData;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private SmartFoxClient mArtFoxClient;
	private IntentFilter filter;
	private String classID="0";//默认是0 表示科室
	private double distance;
	private TagsGridView mGridView;
	private List<ShopEntityClassify> mListGrid;
	private ExpandGridListAdapter mGridAdapter;
	private String areCode="0";//地区编码 默认是0
	private boolean booleanExtra;//true 表示非医疗
	private ImageView imageRigh;
	private PopupWindow pop;
//	private String class_NAME;//标题科室显示名字
	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(CoreService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result =  intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(ServerCenterDoctorListActivity.this,R.string.groupNewFail);
					}else {
						FriendHttpUtil.requestAttentionTofriendsResult(ServerCenterDoctorListActivity.this, cacheCustomerInfoEntity, mAppData);
						adapter.notifyDataSetChanged();
						}
			}else if(action.equals(SFSEvent.CONNECTION_LOST)){
						ToastUtil.showShort(ServerCenterDoctorListActivity.this, "正在重新连接...");
					}
			else if (action.equals(CoreService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					adapter.notifyDataSetChanged();
					}}
		}
	};
	private View mainView;
	private View wheelView;
//	private TextView mTextTile;
	private LinearLayout mAddViewTitle;
	
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.server_center_doctor_list);
		mAppData = HTalkApplication.getAppData();
		mArtFoxClient = SmartFoxClient.getSmartFoxClient();
		initTitle();
		initView();
		dictionaryHelper = DictionaryHelper.getInstance(this);
		booleanExtra = getIntent().getBooleanExtra("isDoc",false);
		id = getIntent().getStringExtra("id");
		initData(classID);
		queryData();//封装位置信息
	}
	
	/**
	 * 点击编辑的时候,开启分线程查询并封转城市数据及信息层面数据
	 */
	private void queryData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<Map<String,String>> list = new ArrayList<Map<String,String>>();
				cityMap.put("全部",list);
				proList = dictionaryHelper.setCityData(ServerCenterDoctorListActivity.this, cityMap);
				Map<String,String> map = new HashMap<String,String>();
				map.put("name","全部");
				map.put("code","0");
				proList.add(0,map);
				Set<String> set = cityMap.keySet();
				for (String string : set) {
					List<Map<String, String>> maps = cityMap.get(string);
					maps.add(0,map);
				}
			}
		}).start();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		filter = new IntentFilter();
		filter.addAction(CoreService.ACTION_COLLECT_FRIEND);
		filter.addAction(CoreService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			Intent intent = new Intent(getApplicationContext(),DoctorMainActivity.class);
			intent.putExtra("id", arrayList.get(position-1).getId());
			startActivity(intent);
		} catch (Exception e) {
		}
	}
	
	private void initData(String classID) {
		HttpRestClient.doHttpSalonSavant(booleanExtra,id,SmartFoxClient.getLoginUserId(),String.valueOf(pageNum),classID,areCode,
				new ObjectHttpResponseHandler(this) {
			@Override
			public Object onParseResponse(String content) {
//				onparseJson(content);
				return content;
			}
			
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				onparseJson(response.toString());
				if(pageNum==1){
					if(mListGrid.size()==1){
						imageRigh.setBackgroundResource(R.drawable.arrows);
						mGridView.setVisibility(View.GONE);
						mAddViewTitle.setVisibility(View.GONE);
					}else{
						mAddViewTitle.setVisibility(View.VISIBLE);
						imageRigh.setBackgroundResource(R.drawable.arrows_down_city);
						mGridView.setVisibility(View.VISIBLE);
					}
				}
				
					if(arrayList.size()==0){
						ToastUtil.showToastPanl("没有记录");
						findViewById(R.id.top_line).setVisibility(View.GONE);
						findViewById(R.id.clear_all).setVisibility(View.VISIBLE);
					}else{
						pageNum++;
						findViewById(R.id.top_line).setVisibility(View.VISIBLE);
						findViewById(R.id.clear_all).setVisibility(View.GONE);
					}
					
					mGridAdapter.notifyDataSetChanged();
					adapter.notifyDataSetChanged();
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				try {
					mPullToRefreshListView.onRefreshComplete();
				} catch (Exception e) {
				}
			}
		});
	}
	protected void onparseJson(String content) {
		try {
			JSONObject object=new JSONObject(content);
			arrayList.addAll(FriendHttpUtil.jsonAnalysisFriendEntity(object.getJSONArray("list").toString(),false));
//			if(mListGrid.size()==0){
			mListGrid.clear();
			ShopEntityClassify shopEntityClassify = new ShopEntityClassify();
			shopEntityClassify.setCLASS_NAME("全部");
			mListGrid.add(shopEntityClassify);
			mListGrid.addAll(ShopEntityClassify.SearchDoctorsKESHIToList(object.getJSONArray("centerClass").toString()));	
//			}
		} catch (JSONException e) {
		}
	}
	private int addViewCount=1;//表示添加控件的位置
	
	private void initView() {
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setText("地点");
		titleRightBtn2.setBackgroundResource(R.drawable.server_doctor_list_address);
		titleTextV.setText(getIntent().getStringExtra("title"));
		titleLeftBtn.setOnClickListener(this);
		adapter = new DoctorAdapter(ServerCenterDoctorListActivity.this, arrayList,false);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		mListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		adapter.setonClickFriendAttentionListener(this);
		adapter.setonClickFriendHeadListener(this);
		mPullToRefreshListView.setOnRefreshListener(this);
		imageRigh = (ImageView)findViewById(R.id.viewRigh);
		imageRigh.setOnClickListener(this);
		
		mListGrid = new ArrayList<ShopEntityClassify>();
		mGridView=(TagsGridView)findViewById(R.id.grid);
		mGridAdapter = new ExpandGridListAdapter(mListGrid,this);
		mGridView.setAdapter(mGridAdapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				arrayList.clear();
				pageNum=1;
				final ShopEntityClassify entityClassify = mListGrid.get(position);
				TextView textView=new TextView(ServerCenterDoctorListActivity.this);
				textView.setText(">"+entityClassify.getCLASS_NAME());
				textView.setTag(0, entityClassify);//0表示存的对象
				textView.setTag(1,addViewCount);//1表示存的第几个控件
				mAddViewTitle.addView(textView);
				addViewCount++;
				textView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if("全部".equals(entityClassify.getCLASS_NAME())){
							classID="0";
						}else{
							classID=entityClassify.getCLASS_ID();
							//首先移除后面的控件  
							mAddViewTitle.removeViews(Integer.valueOf(v.getTag(1).toString()), addViewCount);
							addViewCount=Integer.valueOf(v.getTag(1).toString());
						}
					}
				});
				
				initData(classID);
				
				
				
			/*	if("全部".equals(class_NAME)){
					classID="0";
				}else{
					classID=mListGrid.get(position).getCLASS_ID();
				}
				mTextTile.setText("科室选择>"+class_NAME);*/
					
			}
		});
		
		LayoutInflater inflater = LayoutInflater.from(this);
		mainView = inflater.inflate(R.layout.server_center_doctor_list, null);
		wheelView = inflater.inflate(R.layout.wheel, null);
		wheelView.findViewById(R.id.wheel_cancel).setOnClickListener(this);
		wheelView.findViewById(R.id.wheel_sure).setOnClickListener(this);
		pop = new PopupWindow(wheelView, LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
//		mTextTile = (TextView)findViewById(R.id.text_yaopin1);
		mAddViewTitle=(LinearLayout)findViewById(R.id.line_title);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		case R.id.title_right2:
			setCity();
			break;
		case R.id.viewRigh:
			if(mGridView.getVisibility()== View.VISIBLE){
				imageRigh.setBackgroundResource(R.drawable.arrows);
				mGridView.setVisibility(View.GONE);}
			else{
				imageRigh.setBackgroundResource(R.drawable.arrows_down_city);
				mGridView.setVisibility(View.VISIBLE);
				}
				break;
		case R.id.wheel_sure:
			pageNum=1;
			if (pop != null)
				pop.dismiss();
			if (WheelUtils.getCurrent() != null) {
				String name = WheelUtils.getCurrent();
				if(name.toString().equals("全部-全部")){
					name="全部";
				}else if(name.contains("-")){
					name=name.substring(name.indexOf("-")+1, name.length());
				}
				titleRightBtn2.setText(name);
				areCode=WheelUtils.getCode();
				arrayList.clear();
				initData(classID);
			}
			break;
		case R.id.wheel_cancel:
			if (pop != null)
				pop.dismiss();
			break;
		}
	}
	
	/**
	 * 设置滚轮 城市数据
	 */
	private void setCity() {
		if (proList == null || cityMap == null) {
		} else {
			WheelUtils.setDoubleWheel(this, proList, cityMap, mainView, pop,wheelView);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(pop!=null){
			pop.dismiss();
			pop=null;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode,data);
		switch (requestCode) {
		case 1000:
			if (data!= null &&data.hasExtra("mFriendInformUI")) {
				if ((Integer) data.getExtras().get("position") != -1) {
					CustomerInfoEntity entity = (CustomerInfoEntity) data.getExtras().get("mFriendInformUI");
					if (distance != 0) {
						entity.setDistance(distance);
					}
					arrayList.set((Integer) data.getExtras().get("position"),entity);
					adapter.notifyDataSetChanged();
				}
			}
			break;
		}
	}
	
	
	
	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		initData(classID);
	}
	
	
	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		try {
			Intent intent = new Intent(getApplicationContext(),DoctorMainActivity.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		try {
			ServerCenterDoctorListActivity.this.unregisterReceiver(receiver);
		} catch (Exception e) {
		}
	}
	
	public void expanNotifyDataSetChanged() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
		
	}
	
	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity, int positon) {
		if (!SmartControlClient.getControlClient().isConnected()) {
			ToastUtil.showLong(this, "与服务器连接错误");
			return;
		}
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this, null, entity);
	}

}
